package com.example.zbh.dsliao.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.example.zbh.dsliao.R;
import com.example.zbh.dsliao.constant.Constant;
import com.example.zbh.dsliao.db.DatabaseHelper;
import com.example.zbh.dsliao.db.entity.CarrouselPic;
import com.example.zbh.dsliao.db.entity.ForYouRecommend;
import com.example.zbh.dsliao.db.entity.HotSongMenu;
import com.example.zbh.dsliao.db.entity.NewSong;
import com.example.zbh.dsliao.db.entity.NewSongImg;
import com.example.zbh.dsliao.db.entity.RadioSet;
import com.example.zbh.dsliao.db.entity.SongRecommend;
import com.example.zbh.dsliao.model.entity.SongRecommedResult;
import com.example.zbh.dsliao.model.entity.SongRecommendContent;
import com.example.zbh.dsliao.presenter.RecommendPresenter;
import com.example.zbh.dsliao.ui.adapter.RVForYouRecommendAdapter;
import com.example.zbh.dsliao.ui.adapter.RVHotSongMenuAdapter;
import com.example.zbh.dsliao.ui.adapter.RVNewSongAdapter;
import com.example.zbh.dsliao.ui.adapter.RVSongRecommendAdapter;
import com.example.zbh.dsliao.ui.adapter.RVTypeAdapter;
import com.example.zbh.dsliao.ui.adapter.RadioSetAdapter;
import com.example.zbh.dsliao.ui.adapter.ViewPagerAdapter;
import com.example.zbh.dsliao.ui.viewinterface.ShowDownLoaderResultListener;
import com.example.zbh.dsliao.ui.viewinterface.ShowRecommendListener;
import com.example.zbh.dsliao.utils.FullyGridLayoutManager;
import com.example.zbh.dsliao.utils.net.VolleySingleton;
import com.example.zbh.dsliao.view.CubeOutTransformer;
import com.example.zbh.dsliao.view.ViewPagerScroller;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yaolin on 15/11/19.
 */
public class RecommendFragment extends MVPBaseFragment<ShowRecommendListener, RecommendPresenter> implements ViewPager.OnPageChangeListener, ShowRecommendListener {
    private TextView dateTv;
    //数据库帮助类
    private DatabaseHelper helper;

    private ViewPager viewPager;                        //轮播viewpager
    private ViewPagerAdapter adapter;                   //轮播适配器
    private List<CarrouselPic> lists;

    private RecyclerView rVForYouRecommend;             //为你推荐列表
    private RVForYouRecommendAdapter forYouAdapter;     //为你推荐表的适配器

    private LinearLayout linearLayout;
    private ImageView[] small_circle = new ImageView[6];


    private RecyclerView rVType;                        //歌曲分类列表
    private ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    private int[] image = {R.mipmap.type_one, R.mipmap.type_two,
            R.mipmap.type_three, R.mipmap.type_four};   //歌曲分类图片
    private RVTypeAdapter typeAdapter;                  //歌曲分类适配器


    private RecyclerView rVHotSongMenu;                 //热门歌单列表
    private RVHotSongMenuAdapter hotAdapter;            //热门歌单适配器

    private RecyclerView rVSongRecommend;               //歌曲推荐列表
    private RVSongRecommendAdapter songAdapter;         //歌曲推荐适配器


    private RecyclerView rvNewSong;                     //最新歌曲列表
    private RVNewSongAdapter newAdapter;                //最新歌曲适配器

    private NetworkImageView newSongImg;                //最新歌曲图片
    private TextView titleTv;                           //最新歌曲标题
    private TextView messageTv;                         //最新歌曲小标题
    private NewSongImg newSongImage;


    private RecyclerView rVRadioSet;                   //电台节目列表
    private RadioSetAdapter radioAdapter;              //电台节目适配器

    //网络请求
    VolleySingleton volleySingleton = VolleySingleton.getInstance();
    //二级缓存
    private ImageLoader imageLoader;
    private ArrayList<CarrouselPic> pic;
    private Context context;
    private ImageView backstage_play;   //后台播放
    private int size = 0;                    //计数器
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }
    //延时跳转对象
    private Handler handler;
    //当前组件的下标
    private int currentItem = 0;
    //最大的下标
    private int maxItem = 0;
    /**
     * 子线程
     **/
    private Runnable r = new Runnable() {
        @Override
        public void run() {
            int index = viewPager.getCurrentItem();
            viewPager.setCurrentItem(++index);
            //延时2秒改变下标
            handler.postDelayed(r, 2000);
        }
    };
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_recommend, null);
        //初始化控件
        initView(v);
        return v;
    }
    @Override
    protected void initData() {
        //初始化helper
        helper = DatabaseHelper.getInstance();
        //获得系统日期
        getDate();
        //初始化handler
        handler = new Handler();
        //初始化imageLoder
        imageLoader = volleySingleton.getImageLoader();
        //查询所有
        lists = helper.queryAllCarousel();
        if (lists == null || lists.size() == 0) {
            //轮播图网络请求
            createPresenter().startCarouselConnection(getCarouselPath());
        } else {
            adapter.addData(lists);
            handler.postDelayed(r, 2000);
            initCircle();
        }
        List<ForYouRecommend> forYouList = helper.queryAllForYouRrcommend();
        if (forYouList == null || forYouList.size() == 0) {
            //为你推荐解析
            createPresenter().startForYouRecommendConnection(getForYouRecommendPath());
        } else {
            forYouAdapter.addData(forYouList);
        }
        List<HotSongMenu> hotSongMenusList = helper.queryAllHotSongMenu();
        if (hotSongMenusList == null || hotSongMenusList.size() == 0) {
            // 热门歌单解析
            createPresenter().startHotSongMenuConnection(getHotSongMenuPath());
        } else {
            hotAdapter.addData(hotSongMenusList);
        }
        List<SongRecommend> songRecommends = helper.queryAllSongRecommend();
        if (songRecommends == null || songRecommends.size() == 0) {
            //歌曲推荐解析
            createPresenter().startSongRecommendConnextion(getSongRecommendPath());
        } else {
            songAdapter.addData(songRecommends);
        }
        //最新歌曲图片
        createPresenter().startNewSongImgConnection(getNewSongImgPath());
        List<NewSong> newSongs = helper.queryAllNewSong();
        if (newSongs == null || newSongs.size() == 0) {
            //最新歌曲解析
            createPresenter().startNewSongConnection(getNewSongPath());
        } else {
            newAdapter.addData(newSongs);
        }
        List<RadioSet> radioSets = helper.queryAllRadioSet();
        if (radioSets == null || radioSets.size() == 0) {
            //电台节目解析
            createPresenter().startRadioSetConnection(getRadioSetPath());
        } else {
            radioAdapter.addData(radioSets);
        }
    }

    //初始化指挥家
    @Override
    protected RecommendPresenter createPresenter() {
        return new RecommendPresenter(this);
    }
    //得到轮播图的地址
    public String getCarouselPath() {
        return Constant.CAROUSELURL;
    }
    //得到为你推荐地址
    public String getForYouRecommendPath() {
        return Constant.FORYOURECOMMENDURL;
    }
    //得到热门歌单地址
    public String getHotSongMenuPath() {
        return Constant.HOTSONGMENUURL;
    }
    //得到歌曲推荐地址
    public String getSongRecommendPath() {
        return Constant.SONGRECOMMENDPATH;
    }
    //最新歌曲图片地址
    public String getNewSongImgPath() {
        return Constant.NEWSONGIMGURL;
    }
    //得到最新歌曲地址
    public String getNewSongPath() {
        return Constant.NEWSONGURL;
    }
    //得到电台地址
    public String getRadioSetPath() {
        return Constant.RADIOSETURL;
    }
    //将轮播结果展示出来
    @Override
    public void showCarouselResult(List<CarrouselPic> lists) {
        this.lists = lists;
        adapter.addData(lists);
        //删除所有
        helper.deleteAllCarousel();
        //添加数据
        helper.saveCarousel(lists);
        handler.postDelayed(r, 2000);
        //创建小圆点
        initCircle();
    }
    //将为你推荐的结果展示出来
    @Override
    public void showForYouRecommendResult(List<ForYouRecommend> list) {
        forYouAdapter.addData(list);
        //删除所有
        helper.deleteAllForYouRrcommend();
        //添加数据
        helper.saveForYouRecommend(list);
    }

    //将热门歌单结果显示出来
    @Override
    public void showHotSongMenuResult(List<HotSongMenu> list) {
        hotAdapter.addData(list);
        //删除所有
        helper.deleteAllHotSongMenu();
        //添加数据
        helper.saveHotSongMenu(list);

    }

    //将歌曲推荐结果显示出来
    @Override
    public void showSongRecommendResult(List<SongRecommend> list) {
        songAdapter.addData(list);
        //删除所有
        helper.deleteAllSongRecommend();
        //添加数据
        helper.saveSongRecommend(list);
    }

    //最新歌曲图片解析结果显示出来
    @Override
    public void showNewSongImgResult(JSONObject object) {

        try {
            String title = object.getString("title");
            String pic = object.getString("pic");
            String message = object.getString("message");
            titleTv.setText(title);
            messageTv.setText(message);
            getBitmap(pic, newSongImg);
            //删除所有
            helper.deleteAllNewSongImg();
            //添加数据
            newSongImage = new NewSongImg(null, title, pic, message);
            helper.saveNewSongImg(newSongImage);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //最新歌曲解析显示
    @Override
    public void showNewSongResult(List<NewSong> list) {
        newAdapter.addData(list);
        //删除所有
        helper.deleteAllNewSong();
        //添加数据
        helper.saveNewSong(list);
    }

    //电台节目解析结果显示
    @Override
    public void showRadioSetResult(List<RadioSet> list) {
        radioAdapter.addData(list);
        //删除所有
        helper.deleteAllRadioSet();
        //添加数据
        helper.saveRadioSet(list);

    }


    private void getBitmap(String url, NetworkImageView imageView) {
        imageView.setDefaultImageResId(R.mipmap.music_cache_icon);
        imageView.setErrorImageResId(R.mipmap.music_cache_icon);
        imageView.setImageUrl(url, imageLoader);
    }

    /**
     * 创建小圆点
     **/
    private void initCircle() {
        //viewpager添加监听事件
        viewPager.addOnPageChangeListener(this);
        ImageView imageView;
        for (int i = 0; i < lists.size(); i++) {
            imageView = new ImageView(context);
            LinearLayout.LayoutParams layoutParams = new
                    LinearLayout.LayoutParams(20, 20);
            layoutParams.setMargins(10, 10, 10, 10);
            imageView.setLayoutParams(layoutParams);
            small_circle[i] = imageView;
            if (i == 0) {
                imageView.setImageResource(R.mipmap.small_circle_select);
            } else {
                imageView.setImageResource(R.mipmap.small_circle);
            }

            linearLayout.addView(small_circle[i]);
        }
    }

    /**
     * 获得系统日期
     **/
    private void getDate() {
        Calendar c = Calendar.getInstance();
        int day = c.get(Calendar.DAY_OF_MONTH);
        dateTv.setText(day + " ");
    }
    /**
     * 初始化组件
     **/
    private void initView(View view) {
        dateTv = (TextView) view.findViewById(R.id.dateTv);
        //初始化---viewpager
        viewPager = (ViewPager) view.findViewById(R.id.viewpager);
        //第三方viewpager特效
        viewPager.setPageTransformer(true, new CubeOutTransformer());
        //调用  设置ViewPager的滑动速度  方法
        initViewPagerScroll();
        //初始化---轮播适配器
        adapter = new ViewPagerAdapter(context);
        //绑定适配器
        viewPager.setAdapter(adapter);
        linearLayout = (LinearLayout) view.findViewById(R.id.linearLayout);
        //初始化---为你推荐列表
        rVForYouRecommend = (RecyclerView) view.findViewById(R.id.rVForYouRecommend);
        //布局管理器
        FullyGridLayoutManager gm = new FullyGridLayoutManager(context, 2);
        //设置布局管理器
        rVForYouRecommend.setLayoutManager(gm);
        //初始化---为你推荐适配器
        forYouAdapter = new RVForYouRecommendAdapter(context);
        //绑定适配器
        rVForYouRecommend.setAdapter(forYouAdapter);
        //初始化---歌曲分类列表
        rVType = (RecyclerView) view.findViewById(R.id.rVType);
        FullyGridLayoutManager typeLm = new FullyGridLayoutManager(context, 2);
        rVType.setLayoutManager(typeLm);
        //初始化---歌曲分类适配器
        typeAdapter = new RVTypeAdapter(context);
        typeAdapter.addData(image);
        //绑定适配器
        rVType.setAdapter(typeAdapter);
        //初始化---热门歌单列表
        rVHotSongMenu = (RecyclerView) view.findViewById(R.id.rVHotSongMenu);
        FullyGridLayoutManager hotLm = new FullyGridLayoutManager(context, 3);
        rVHotSongMenu.setLayoutManager(hotLm);
        //初始化---热门歌单适配器
        hotAdapter = new RVHotSongMenuAdapter(context);
        rVHotSongMenu.setAdapter(hotAdapter);
        //初始化---歌曲推荐列表
        rVSongRecommend = (RecyclerView) view.findViewById(R.id.rVSongRecommend);
        FullyGridLayoutManager songLm = new FullyGridLayoutManager(context, 1);
        rVSongRecommend.setLayoutManager(songLm);
        //初始化---歌曲推荐适配器
        songAdapter = new RVSongRecommendAdapter(context);
        rVSongRecommend.setAdapter(songAdapter);
        //初始化---最新歌曲图片
        newSongImg = (NetworkImageView) view.findViewById(R.id.newSongImg);
        //初始化---最新歌曲标题
        titleTv = (TextView) view.findViewById(R.id.titleTv);
        //初始化---最新歌曲小标题
        messageTv = (TextView) view.findViewById(R.id.messageTv);
        //初始化---最新歌曲列表
        rvNewSong = (RecyclerView) view.findViewById(R.id.rvNewSong);
        FullyGridLayoutManager newLm = new FullyGridLayoutManager(context, 2);
        rvNewSong.setLayoutManager(newLm);
        //初始化---最新歌曲适配器
        newAdapter = new RVNewSongAdapter(context);
        rvNewSong.setAdapter(newAdapter);
        //初始化---电台节目列表
        rVRadioSet = (RecyclerView) view.findViewById(R.id.rVRadioSet);
        FullyGridLayoutManager radioLm = new FullyGridLayoutManager(context, 3);
        rVRadioSet.setLayoutManager(radioLm);
        //初始化---电台节目适配器
        radioAdapter = new RadioSetAdapter(context);
        rVRadioSet.setAdapter(radioAdapter);
    }


    /**
     * 设置ViewPager的滑动速度
     */
    private void initViewPagerScroll() {
        try {
            Field mScroller = null;
            mScroller = ViewPager.class.getDeclaredField("mScroller");
            mScroller.setAccessible(true);
            ViewPagerScroller scroller = new ViewPagerScroller(
                    viewPager.getContext());
            mScroller.set(viewPager, scroller);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        // handler.removeCallbacks(r);
    }
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        for (int i = 0; i < lists.size(); i++) {
            small_circle[i].setImageResource(R.mipmap.small_circle);
        }
        small_circle[(position % lists.size())].setImageResource(R.mipmap.small_circle_select);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


}

